package com.nartosoft.tubuloader;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JFrame;

/**
 * @author mf
 * 
 * Builds a PicUploader depending on the arguments passed on commandline and
 * uses it to upload the provided images.
 */


public class TubuloaderRunner {
	private static final String TEMPLATE_URL_PLACEHOLDER = "%s";

	private static final String DEFAULT_TEMPLATE = TEMPLATE_URL_PLACEHOLDER;

	private static EventDispatcher events;

	private static LogfileWriter createLogfileWriter(Configuration options)
			throws IOException {
		if (options.isLogFileFormatSet()) {
			return new LogfileWriter(options.getLogFileName(), options
					.isImageFileLoggingSet(), options.isUrlLoggingSet(), options
					.isErrorLoggingSet());
		}
		else {
			// use default logfile format: log all available data
			return new LogfileWriter(options.getLogFileName(), true, true, true);
		}
	}

	private static HtmlFileWriter createHtmlFileWriter(Configuration options)
			throws IOException {
		if (options.getHtmlFileName() == null) {
			return null;
		}
		return new HtmlFileWriter(options.getHtmlFileName());
	}

	private static String createClipboardTemplate(Configuration options) {
		if (!options.isTemplateSet()) {
			return DEFAULT_TEMPLATE;
		}
		final String template = options.getTemplate();
		if (template == null || template.indexOf(TEMPLATE_URL_PLACEHOLDER) == -1) {
			events.notifyError("invalid template, must contain url placeholder "
					+ TEMPLATE_URL_PLACEHOLDER);
			return DEFAULT_TEMPLATE;
		}
		return template;
	}

	private static UploadDoneDialog createUploadDoneDialog(Configuration options) {
		if (options.getSummaryTime() == null) {
			events.notifyError("summary display time not specified");
			return null;
		}
		return new UploadDoneDialog(new JFrame(), Integer.parseInt(options
				.getSummaryTime()));
	}

	private static TubuloaderTray createPicUploaderTray(String fileName, int number) {
		return new TubuloaderTray(fileName, number);
	}
	
	private static void setProxy(String proxyString) {
		final int portSeparatorPos = proxyString.lastIndexOf(':');
		if (portSeparatorPos == -1 || portSeparatorPos != proxyString.indexOf(':')) {
			events.notifyError("invalid proxy string: " + proxyString);
			return;
		}

		final Properties properties = System.getProperties();
		properties.put("proxySet", "true");
		properties.put("proxyHost", proxyString.substring(0, portSeparatorPos));
		properties.put("proxyPort", proxyString.substring(portSeparatorPos + 1));
	}

	public static void init(Configuration options) {
		events = new EventDispatcher();
		events.addEventListener(new DebugWriter());
		events.addEventListener(new ClipboardWriter(options.isVerboseSet(),
				createClipboardTemplate(options)));
		if (options.isLogFileSet()) {
			try {
				events.addEventListener(createLogfileWriter(options));
			}
			catch (IOException e) {
				events.notifyError("could not initialise logfile: "
						+ options.getLogFileName());
			}
		}

		if (options.isHtmlFileSet()) {
			try {
				events.addEventListener(createHtmlFileWriter(options));
			}
			catch (IOException e) {
				events.notifyError("could not initialise HTML file: "
						+ options.getHtmlFileName());
			}
		}

		if (options.isTrayiconSet()) {
    	  events.addEventListener(createPicUploaderTray(options.getTrayiconFile(), options.getFileNames().size()));
		}
		
		if (options.isSummarySet()) {
			try {
				events.addEventListener(createUploadDoneDialog(options));
			}
			catch (Exception e) {
				events.notifyError("could not initialise Dialog: " + e.getMessage());
			}
		}

		if (options.isSoundSet()) {
			if (!(new File(options.getSoundFile()).exists())) {
				events.notifyError("could not load sound file: "
						+ options.getSoundFile());
			}
			else {
				try {
					events.addEventListener(new SoundPlayer(options.getSoundFile()));
				}
				catch (Exception e) {
					events.notifyError("could not create sound clip: " + e.getMessage());
				}
			}
		}

		if (options.isProxySet()) {
			setProxy(options.getProxy());
		}
	}
	
	public static void main(String[] args) {
		Configuration options = null;
		try {
			if(args[0].endsWith(".config")) {
			  options = new FileConfiguration(args);
			}
			else {
				System.exit(-1);
			}
		}catch(Exception e) {
			e.printStackTrace();
			System.exit(-1);
		}
		init(options);
		try {
			new Tubuloader(events).uploadFiles(options.getFileNames(), options);
		}catch(Exception e) {
			e.printStackTrace();
			events.notifyError("error occured: " + e.getMessage());
		}
		System.exit(0);
	}
}
